// utils/request.js
const app = getApp()

/**
 * 网络请求封装
 */
function request(url, method, data, header = {}) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: app.globalData.baseUrl + url,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token') || '',
        ...header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            resolve(res.data.data)
          } else {
            showErrorToast(res.data.message || '请求失败')
            reject(res.data)
          }
        } else {
          showErrorToast(`网络错误 ${res.statusCode}`)
          reject(res)
        }
      },
      fail: (err) => {
        showErrorToast('网络连接失败')
        reject(err)
      }
    })
  })
}

/**
 * GET请求
 */
function get(url, data = {}) {
  return request(url, 'GET', data)
}

/**
 * POST请求
 */
function post(url, data = {}) {
  return request(url, 'POST', data)
}

/**
 * PUT请求
 */
function put(url, data = {}) {
  return request(url, 'PUT', data)
}

/**
 * DELETE请求
 */
function del(url, data = {}) {
  return request(url, 'DELETE', data)
}

/**
 * 显示错误提示
 */
function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    icon: 'none',
    duration: 2000
  })
}

module.exports = {
  get,
  post,
  put,
  del
}    